package cn.b.sky.mes.andon.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import cn.b.sky.mes.andon.dao.AndonTemplateAttributeDao;
import cn.b.sky.mes.andon.dao.AndonTemplateDao;
import cn.b.sky.mes.andon.model.AndonTemplate;
import cn.b.sky.mes.andon.model.AndonTemplateAttribute;
import cn.b.sky.mes.andon.model.condition.AndonTemplateAttributeCondition;
import cn.b.sky.mes.andon.model.condition.AndonTemplateCondition;
import cn.b.sky.mes.andon.service.AndonTemplateService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.Page;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;

/**
 * 
 * <strong>Title : AndonTemplateServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.andon.service.impl<br></strong>
 * <strong>Description : </strong>暗灯模板操作业务类实现<br> 
 * <strong>Create on : 2016-10-14 下午01:19:04<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong>
 */
@Service("andonTemplateService")
public class AndonTemplateServiceImpl implements AndonTemplateService {

  private static final Logger LOGGER = LoggerFactory.getLogger(AndonTemplateServiceImpl.class);

  @Resource
  private AndonTemplateDao andonTemplateDao;

  @Resource
  private AndonTemplateAttributeDao andonTemplateAttributeDao;

  @Override
  public int insertAndonTemplate(AndonTemplate data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.insertAndonTemplate(data);
  }

  @Override
  public int updateAndonTemplate(AndonTemplate data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.updateAndonTemplate(data);
  }

  @Override
  public BatchJobReport deleteAndonTemplate(AndonTemplate data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.deleteAndonTemplateByPrimaryKey(data.getSiteCode(), data.getTemplateCode());
  }

  @Override
  public long getAndonTemplatesCount() {
    return this.andonTemplateDao.getAndonTemplatesCount();
  }

  @Override
  public List<AndonTemplate> selectAndonTemplates() {
    return this.andonTemplateDao.selectAndonTemplates();
  }

  @Override
  public BatchJobReport deleteAndonTemplateByPrimaryKey(String siteCode, String templateCode) {
    String cause = "";
    Boolean success = true;
    try {
      this.andonTemplateDao.deleteAndonTemplateByPrimaryKey(siteCode, templateCode);
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(templateCode, cause, success);
  }

  @Override
  public AndonTemplate getAndonTemplateByPrimaryKey(String siteCode, String templateCode) {
    return this.andonTemplateDao.getAndonTemplateByPrimaryKey(siteCode, templateCode);
  }

  @Override
  public boolean existAndonTemplateByPrimaryKey(String siteCode, String templateCode) {
    return this.andonTemplateDao.existAndonTemplateByPrimaryKey(siteCode, templateCode);
  }

  @Override
  public boolean existsAndonTemplateByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.existsAndonTemplateByCondition(condition);
  }

  @Override
  public AndonTemplate getAndonTemplateByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.getAndonTemplateByCondition(condition);
  }

  @Override
  public List<AndonTemplate> selectAndonTemplatesByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.selectAndonTemplatesByCondition(condition);
  }

  @Override
  public List<AndonTemplate> selectAndonTemplatePageDataByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.selectAndonTemplatePageDataByCondition(condition);
  }

  @Override
  public Page selectAndonTemplatePageByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    condition.setData(this.andonTemplateDao.selectAndonTemplatePageDataByCondition(condition));
    condition.setTotalCount(this.andonTemplateDao.getAndonTemplatesCountByCondition(condition));
    return condition;
  }

  @Override
  public long getAndonTemplatesCountByCondition(AndonTemplateCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.andonTemplateDao.getAndonTemplatesCountByCondition(condition);
  }

  @Override
  public AndonTemplate getAndonTemplateAndAttributesByPrimaryKey(String siteCode, String templateCode) {
    AndonTemplate andonTemplate = this.andonTemplateDao.getAndonTemplateDetailByPrimaryKey(siteCode, templateCode);
    if (null != andonTemplate) {
      AndonTemplateAttributeCondition attributeCondition = new AndonTemplateAttributeCondition();
      attributeCondition.setSiteCode(siteCode);
      attributeCondition.setTemplateCode(templateCode);
      andonTemplate.setAndonTemplateAttributeList(
          this.andonTemplateAttributeDao.selectAndonTemplateAttributesByCondition(attributeCondition));
    }
    return andonTemplate;
  }

  @Override
  public boolean insertOrUpdateAndonTemplateAndAttributes(AndonTemplate andonTemplate) {
    if (null == andonTemplate) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }

    int n = 0;
    andonTemplate.preProcessingToStore();
    if (this.andonTemplateDao.existAndonTemplateByPrimaryKey(andonTemplate.getSiteCode(),
        andonTemplate.getTemplateCode())) {
      //如果存在模版记录则进行修改操作
      n = this.andonTemplateDao.updateAndonTemplate(andonTemplate);
    } else {
      //如果不存在模版记录则进行新增操作
      n = this.andonTemplateDao.insertAndonTemplate(andonTemplate);
    }

    if (n == 1) {
      //修改模版数据后针对自定义属性进行更新，采用先删除后新增的方式
      AndonTemplateAttributeCondition attributeCondition = new AndonTemplateAttributeCondition();
      attributeCondition.setSiteCode(andonTemplate.getSiteCode());
      attributeCondition.setTemplateCode(andonTemplate.getTemplateCode());
      this.andonTemplateAttributeDao.deleteAndonTemplateAttributeByCondition(attributeCondition);

      if (!CollectionUtils.isEmpty(andonTemplate.getAndonTemplateAttributeList())) {
        for (AndonTemplateAttribute andonTemplateAttribute : andonTemplate.getAndonTemplateAttributeList()) {
          if (StringUtils.isNotBlank(andonTemplateAttribute.getAttributeValue())) {
            andonTemplateAttribute.setSiteCode(andonTemplate.getSiteCode());
            andonTemplateAttribute.setTemplateCode(andonTemplate.getTemplateCode());
            andonTemplateAttribute.setAndonTypeCode(andonTemplate.getAndonTypeCode());
            this.andonTemplateAttributeDao.insertAndonTemplateAttribute(andonTemplateAttribute);
          }
        }
      }
      return true;
    }

    return false;
  }

  @Override
  public BatchJobReport deleteAndonTemplateAndAttributesByPrimaryKey(String siteCode, String templateCode) {
    String cause = "";
    Boolean success = true;
    try {
      AndonTemplateAttributeCondition attributeCondition = new AndonTemplateAttributeCondition();
      attributeCondition.setSiteCode(siteCode);
      attributeCondition.setTemplateCode(templateCode);
      this.andonTemplateAttributeDao.deleteAndonTemplateAttributeByCondition(attributeCondition);
      this.andonTemplateDao.deleteAndonTemplateByPrimaryKey(siteCode, templateCode);
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(templateCode, cause, success);
  }

  @Override
  public AndonTemplate getAndonTemplateDetail(String siteCode, String templateCode) {
    AndonTemplate template = andonTemplateDao.getAndonTemplateDetailByPrimaryKey(siteCode, templateCode);
    if (null != template) {
      AndonTemplateAttributeCondition attributeCondition = new AndonTemplateAttributeCondition();
      attributeCondition.setSiteCode(siteCode);
      attributeCondition.setTemplateCode(templateCode);
      template.setAndonTemplateAttributeList(
          this.andonTemplateAttributeDao.selectAndonTemplateAttributesByCondition(attributeCondition));
    }
    return template;
  }

}
